package at.dcmspl;

import at.dcmspl.Exceptions.ExportException;
import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJBException;
import javax.ejb.SessionContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.*;

/**
 * Represents a DcmQueue Item which points on a DicomFile in the Filesystem
 * @author Hannes Stornig, Gosch Daniel
 */
@Entity
public class DcmFile implements Serializable {
    private static final long serialVersionUID = 1L;
    @Column(unique=true)
    @EmbeddedId
    private DcmFileCPK id;
    private String filename;
    @Transient
    @Resource SessionContext sc;
    
    @Version
    int versionsnr;
    @Temporal(TemporalType.TIMESTAMP)
    Date createdOn;
    @ManyToOne
    DcmQueue createdFrom;
    @Temporal(TemporalType.TIMESTAMP)
    Date lastEditedOn;
    @ManyToOne
    DcmQueue lastEditedFrom;
       
    @PrePersist
    public void setCreationAttribute(){
        createdOn = new Date();
        createdFrom = parentDcmQueue;
    }
    
    @PreUpdate
    public void editCreationAttribute(){
        lastEditedOn = new Date();
        lastEditedFrom = parentDcmQueue;
    }
       
    @ManyToOne(optional=false)
    @JoinColumn(name="dcmqueue_id")
    private DcmQueue parentDcmQueue;
    
    /**
    * Constructors no Args
    * 
    */
    public DcmFile() {
    }

    /**
    * Constructors
    * @param name
    * @param dcmQueue
    */
    public DcmFile(String name, DcmQueue dcmQueue) throws NamingException, ExportException{
        id = new DcmFileCPK(name,dcmQueue.getId());
        //this.parentDcmQueue = dcmQueue;
        this.exportDcmFile();
    }
    
    /**
    * Getter for DcmFileCPK - This is The Primary Key, it Contains the Queue ID and the DcmFile Name
    * @return DcmFileCPK
    */
    public DcmFileCPK getId() {
        return id;
    }

     /**
    * Setter for DcmFileCPK - This is The Primary Key, it Contains the Queue ID and the DcmFile Name
    * 
    */
    public void setId(DcmFileCPK id) {
        this.id = id;
    }
    
    /**
    * Getter for DcmQueue
    * @return DcmQueue
    */
    public DcmQueue getDcmqueue() {
        return parentDcmQueue;
    }
    
    /**
     * Setter for DcmQueue
     * 
     */
    public void setDcmqueue(DcmQueue dcmqueue) {
        this.parentDcmQueue = dcmqueue;
        this.id.setParentDcmQueueId(dcmqueue.getId());
    }
       
    /**
     * Getter for Name
     * @return String
     */
    public String getName() {
        return id.getName();
    }

    /**
     * Setter for Name
     * @param name 
     */
    public void setName(String name) {
        id.setName(name);
    }
    
    /**
     * Getter for Dateiname
     * @return String
     */
    public String getDateiname() {
        return this.filename;
    }

    /**
     * Setter for Dateiname
     * @param filename 
     */
    public void setDateiname(String filename) {
        this.filename = filename;
    }

    public Date getAngelegtAm() {
        return createdOn;
    }

    public DcmQueue getAngelegtVon() {
        return createdFrom;
    }

    public DcmQueue getParentDcmQueue() {
        return parentDcmQueue;
    }

    public int getVersionsnr() {
        return versionsnr;
    }

    public Date getlastEditedOn() {
            return lastEditedOn;
    }

    public DcmQueue getlastEditedFrom() {
        return lastEditedFrom;
    }
    
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }
    
    @Override
    public boolean equals(Object object) {
        if (!(object instanceof DcmFile)) {
            return false;
        }
        DcmFile other = (DcmFile) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "at.dcmspl.DcmFile[ id=" + id + " name " + id.getName() + " ]";
    }
    
    /**
     * Exports a DcmFile in the Filesystem
     * @throws NamingException 
     */
    private void exportDcmFile() throws NamingException, ExportException{
        try {
            Context context = new InitialContext();
            DcmFileExportRemote dcmFileExporter = (DcmFileExportRemote) context.lookup("java:global/DcmQueueService-ejb/DcmFileExport!at.dcmspl.DcmFileExportRemote"); 
            filename = dcmFileExporter.exportDcmFile(id.getName());
            if(this.filename==null){
                throw new ExportException("Dicom File "+id.getName()+" already exists on the Filesystem ");
            }
            Logger.getLogger(DcmQueueService.class.getName()).log(Level.INFO, "### Export DicomFile {0}",this.filename);
        }
        catch(IOException iox) {
            sc.setRollbackOnly();
            throw new EJBException("Export for DcmFile "+ id.getName() +" failed: "+iox);
        }catch(NamingException nx){
            sc.setRollbackOnly();
            throw new NamingException("JNDI Lookup for DcmFile "+ id.getName() +" failed"+nx);
        }
    }
    
    /**
     * Deletes a DcmFile from the Filesystem
     * @throws NamingException 
     */
    public void deleteDcmFile() throws NamingException{            
            try {
                Context context = new InitialContext();
                DcmFileExportRemote dcmFileExporter = (DcmFileExportRemote) context.lookup("java:global/DcmQueueService-ejb/DcmFileExport!at.dcmspl.DcmFileExportRemote"); 
                dcmFileExporter.removeDcmFile(this.filename+dcmFileExporter.getFINAL_EXTENSION());
            }
            catch(IOException iox) {
                sc.setRollbackOnly();
                throw new EJBException("Deleting DcmFile "+ id.getName() +" failed: "+iox);
            }catch(NamingException nx){
                sc.setRollbackOnly();
                throw new NamingException("JNDI Lookup for "+ id.getName() +" failed"+nx);
            }
    }
    
}
